package com.example.hszpad.modbus;

import android.app.Activity;

import com.intelligt.modbus.jlibmodbus.Modbus;
import com.intelligt.modbus.jlibmodbus.exception.ModbusIOException;
import com.intelligt.modbus.jlibmodbus.exception.ModbusNumberException;
import com.intelligt.modbus.jlibmodbus.exception.ModbusProtocolException;
import com.intelligt.modbus.jlibmodbus.master.ModbusMaster;
import com.intelligt.modbus.jlibmodbus.master.ModbusMasterFactory;
import com.intelligt.modbus.jlibmodbus.tcp.TcpParameters;

/**
 * modbus Tcp连接类
 * Created by Administrator on 2017/4/21.
 */

public class ModbusSocketElectricClient {
    private static final String TAG = "ModbusSocketElectricClient";
    private TcpParameters mTcpParameters;
    private ModbusMaster mModbusMaster;
    private Thread receiveThread;
    private Activity activity;
    private OnReceiveListener onReceiveListener;

    public void setOnReceiveListener(OnReceiveListener onReceiveListener) {
        this.onReceiveListener = onReceiveListener;
    }

    public TcpParameters getTcpParameters() {
        return mTcpParameters;
    }

    public void setTcpParameters(TcpParameters mTcpParameters) {
        this.mTcpParameters = mTcpParameters;
    }

    public ModbusMaster getModbusMaster() {
        return mModbusMaster;
    }


    public ModbusSocketElectricClient(Activity activity) {
        this.activity = activity;
    }

    public void close() {
        if (null != receiveThread) {
            receiveThread.interrupt();
            receiveThread = null;
        }
        if (null != mModbusMaster) {
            if (mModbusMaster.isConnected()) {
                try {
                    mModbusMaster.disconnect();
                } catch (ModbusIOException e) {
                    e.printStackTrace();
                }
            }
            mModbusMaster = null;
        }
    }

    public boolean writeSingleRegister(int slaveId, int address, int val) {
//        Log.e(TAG, ProtocolPackageConvert.byteArrayToHexString(data));
        if (null != mModbusMaster && mModbusMaster.isConnected()) {
            try {
                mModbusMaster.writeSingleRegister(slaveId, address, val);
            } catch (ModbusProtocolException e) {
                e.printStackTrace();
                return true;
            } catch (ModbusNumberException e) {
                e.printStackTrace();
                return true;
            } catch (ModbusIOException e) {
                e.printStackTrace();
                return true;
            }
        }
        return true;
    }

    public boolean conn() {
        close();
        try {
            //创建主机
            mModbusMaster = ModbusMasterFactory.createModbusMasterTCP(mTcpParameters);
            Modbus.setAutoIncrementTransactionId(true);
            //连接
            if (!mModbusMaster.isConnected()) {
                mModbusMaster.connect();
            }
            if (receiveThread == null) {
                receiveThread = new Thread(new ReceiveRunnable(mModbusMaster, activity));
                receiveThread.start();
            }
        } catch (ModbusIOException e) {
            e.printStackTrace();
        }
        return true;
    }

    public class ReceiveRunnable implements Runnable {
        private ModbusMaster master;
        private Activity context;

        public ReceiveRunnable(ModbusMaster master, Activity activity) {
            this.master = master;
            this.context = activity;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    byte[] registerValues = master.readHoldingRegistersBytes(1, 0, 12);
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            ((OnReceiveListener) context).receive(registerValues);
                            if (onReceiveListener != null) {
                                onReceiveListener.receive(0, 12, registerValues);
                            }

                        }
                    });

                    byte[] registerValues2 = master.readHoldingRegistersBytes(1, 5000, 12);
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            ((OnReceiveListener) context).receive(registerValues);
                            if (onReceiveListener != null) {
                                onReceiveListener.receive(5000, 6, registerValues2);
                            }

                        }
                    });

                    byte[] registerValues45 = master.readHoldingRegistersBytes(1, 5045, 6);
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            ((OnReceiveListener) context).receive(registerValues);
                            if (onReceiveListener != null) {
                                onReceiveListener.receive(5045, 6, registerValues45);
                            }

                        }
                    });

                    byte[] registerValues70 = master.readHoldingRegistersBytes(1, 5070, 6);
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            ((OnReceiveListener) context).receive(registerValues);
                            if (onReceiveListener != null) {
                                onReceiveListener.receive(5070, 6, registerValues70);
                            }

                        }
                    });
                    byte[] registerValues3 = master.readHoldingRegistersBytes(1, 5095, 6);
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            ((OnReceiveListener) context).receive(registerValues);
                            if (onReceiveListener != null) {
                                onReceiveListener.receive(5095, 6, registerValues3);
                            }

                        }
                    });

                    byte[] registerValues4 = master.readHoldingRegistersBytes(1, 5120, 6);
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            ((OnReceiveListener) context).receive(registerValues);
                            if (onReceiveListener != null) {
                                onReceiveListener.receive(5120, 6, registerValues4);
                            }

                        }
                    });

                    byte[] registerValues5 = master.readHoldingRegistersBytes(1, 5145, 6);
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            ((OnReceiveListener) context).receive(registerValues);
                            if (onReceiveListener != null) {
                                onReceiveListener.receive(5145, 6, registerValues5);
                            }

                        }
                    });

                    byte[] registerValues5172 = master.readHoldingRegistersBytes(1, 5172, 6);
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            ((OnReceiveListener) context).receive(registerValues);
                            if (onReceiveListener != null) {
                                onReceiveListener.receive(5172, 6, registerValues5172);
                            }

                        }
                    });


//                    while ((len = inputStream.read(buf, 0, buf.length)) != -1) {
//                        p = ProtocolPackageConvert.convertByteArrayToProtocolPackage(buf);
//                        if (null == p) {
//                            if (context instanceof OnReceiveListener) {
//                                context.runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        ((OnReceiveListener) context).parseFail();
//                                    }
//                                });
//                            }
//                        } else {
//                            if (context instanceof OnReceiveListener) {
//                                context.runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        ((OnReceiveListener) context).receive(p);
//                                    }
//                                });
//                            }
//                        }
//                    }
                    Thread.sleep(500);
                } catch (ModbusProtocolException e) {
                    e.printStackTrace();
                    if (context instanceof OnReceiveListener) {
                        context.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                if (onReceiveListener != null) {
                                    onReceiveListener.catchException(e);
                                }
                            }
                        });
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                } catch (ModbusIOException e) {
                    e.printStackTrace();
                    if (context instanceof OnReceiveListener) {
                        context.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (onReceiveListener != null) {
                                    onReceiveListener.catchException(e);
                                }
                            }
                        });
                    }
                } catch (ModbusNumberException e) {
                    e.printStackTrace();
                    if (context instanceof OnReceiveListener) {
                        context.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (onReceiveListener != null) {
                                    onReceiveListener.catchException(e);
                                }
                            }
                        });
                    }
                }
            }
        }
    }

    public interface OnReceiveListener {

        void receive(int start, int quality, byte[] registers);


        void catchException(Exception e);
    }

//    public boolean isRun() {
//        if (null == mSocket || mSocket.isClosed() || !mSocket.isConnected()) {
//            return false;
//        }
//        try {
//            mSocket.sendUrgentData(0xFF);//发送1个字节的紧急数据，默认情况下，服务器端没有开启紧急数据处理，不影响正常通信
//            return true;
//        } catch (Exception se) {
//            return false;
//        }
//    }
}
